<?php

namespace app\api\controller\v1;

use app\common\controller\Api;
use think\Db;

class TeachOnline extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    public function index()
    {
        $scopeType = $this->request->get('scope_type', 'city');
        $scopeId = $this->request->get('scope_id');
        $regionMode = $this->request->get('region_mode', 'self');
        $summaryItems = explode(',', $this->request->get('summary_items', 'class_people,watch_users,watch_times,complete_times,materials,total_duration,avg_duration,engagement'));
        try {
            $data = [];
            if (in_array('class_people', $summaryItems)) $data['class_people'] = Db::name('eb_class_student')->where('status', 1)->where('learn_mode', 'online')->count();
            if (in_array('watch_users', $summaryItems)) $data['watch_users'] = Db::name('live_watch_log')->where('status', 1)->group('user_id')->count();
            if (in_array('watch_times', $summaryItems)) $data['watch_times'] = Db::name('live_watch_log')->where('status', 1)->count();
            if (in_array('complete_times', $summaryItems)) $data['complete_times'] = Db::name('live_watch_log')->where('status', 1)->where('complete_flag', 1)->count();
            if (in_array('materials', $summaryItems)) $data['materials'] = Db::name('course_material')->where('status', 1)->count();
            if (in_array('total_duration', $summaryItems)) $data['total_duration'] = Db::name('live_watch_log')->where('status', 1)->sum('watch_duration');
            if (in_array('avg_duration', $summaryItems)) {
                $total = Db::name('live_watch_log')->where('status', 1)->sum('watch_duration');
                $users = Db::name('live_watch_log')->where('status', 1)->group('user_id')->count();
                $data['avg_duration'] = $users ? round($total / $users, 2) : 0;
            }
            if (in_array('engagement', $summaryItems)) {
                $classPeople = Db::name('eb_class_student')->where('status', 1)->where('learn_mode', 'online')->count();
                $watchUsers = Db::name('live_watch_log')->where('status', 1)->group('user_id')->count();
                $data['engagement'] = $classPeople ? round($watchUsers / $classPeople, 4) : 0;
            }
            return json(['code' => 200, 'msg' => 'OK', 'data' => $data]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => []]);
        }
    }
}